package com.example.bookshop.service.impl;

import com.example.bookshop.VO.CartItemVO;
import com.example.bookshop.entity.Book;
import com.example.bookshop.entity.Cart;
import com.example.bookshop.entity.Order;
import com.example.bookshop.entity.OrderDetail;
import com.example.bookshop.entity.User;
import com.example.bookshop.mapper.*;
import com.example.bookshop.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @auth shanyue
 * @date 2025年06月05日15:16
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private CartMapper cartMapper;

    @Resource
    private BookMapper bookMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Override
    public List<CartItemVO> getCartItemsForCheckout(String username) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return new ArrayList<>();
        }

        List<Cart> cartList = cartMapper.findByUserId(user.getId());
        if (cartList == null || cartList.isEmpty()) {
            return new ArrayList<>();
        }

        List<CartItemVO> cartItems = new ArrayList<>();
        BigDecimal totalPrice = BigDecimal.ZERO;

        for (Cart cart : cartList) {
            Book book = bookMapper.findById(cart.getBookId());
            if (book == null) {
                continue; // 书籍已下架跳过
            }
            CartItemVO item = new CartItemVO();
            item.setCart(cart);
            item.setBook(book);
            BigDecimal subTotal = book.getPrice().multiply(BigDecimal.valueOf(cart.getQuantity()));
            item.setSubTotal(subTotal);
            totalPrice = totalPrice.add(subTotal);
            cartItems.add(item);
        }

        return cartItems;
    }

    @Override
    @Transactional
    public String submitOrder(String username) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return "用户不存在";
        }

        List<Cart> cartList = cartMapper.findByUserId(user.getId());
        if (cartList == null || cartList.isEmpty()) {
            return "购物车为空，无法提交订单";
        }

        // 计算总价，校验库存
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (Cart cart : cartList) {
            Book book = bookMapper.findById(cart.getBookId());
            if (book == null) {
                return "购物车中有已下架商品，请移除";
            }
            if (cart.getQuantity() > book.getStock()) {
                return "库存不足：" + book.getTitle();
            }
            totalPrice = totalPrice.add(book.getPrice().multiply(BigDecimal.valueOf(cart.getQuantity())));
        }

        // 创建订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setTotalPrice(totalPrice);
        order.setCreateTime(new Date());
        orderMapper.insert(order);

        // 创建订单详情，扣库存，清空购物车
        for (Cart cart : cartList) {
            Book book = bookMapper.findById(cart.getBookId());

            OrderDetail detail = new OrderDetail();
            detail.setOrderId(order.getId());
            detail.setBookId(book.getId());
            detail.setQuantity(cart.getQuantity());
            detail.setPrice(book.getPrice());
            orderDetailMapper.insert(detail);

            // 扣库存
            book.setStock(book.getStock() - cart.getQuantity());
            bookMapper.update(book);

            // 删除购物车项
            cartMapper.deleteById(cart.getId());
        }

        return "订单提交成功，订单号：" + order.getId();
    }

    @Override
    public List<Book> getBooks() {
        return bookMapper.findAll();
    }


}
